package com.rural.bus.driver;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.rural.bus.driver.config.BusConstant;
import com.rural.bus.driver.config.MyPreferenceManager;
import com.rural.bus.driver.config.PreferenceKey;
import com.rural.bus.driver.net.MyHttpUtil;
import com.rural.bus.driver.net.OnNetCallback;
import com.rural.bus.driver.net.Url;
import com.rural.bus.driver.utils.CommonTools;
import com.rural.bus.driver.utils.MyLocationClient;
import com.rural.bus.driver.utils.ProgressUtil;
import com.rural.bus.driver.utils.ToastUtil;
import com.rural.bus.driver.utils.VersionUtil;
import com.rural.bus.driver.view.CircleImageView;
import com.rural.bus.driver.view.CommonAlertDialog;
import com.rural.bus.driver.view.SetIsSpecialCarDialog;
import com.rural.bus.driver.view.SetListenOrderDistanceDialog;
import com.rural.bus.driver.view.SetListenOrderDistanceDialog.OnDialogDismissListener;
import com.squareup.picasso.Picasso;

/**
 * @author majie
 */
public class MineActivity extends BaseActivity implements OnClickListener {

	private View tv_my_account, tv_my_all_order, tv_contact_waiter, tv_feedback, tv_check_version;
	private TextView tv_modify_password, tv_listen_order_distance, tv_is_special_car;
	private RelativeLayout rl_listen_order_setting,rl_set_is_special_car;

	private Button btOnline;

	private String userId, userName, photoUrl;
	CommonAlertDialog dialog;
	private int status = 2;
	SetListenOrderDistanceDialog dialogDistance;
	SetIsSpecialCarDialog carDialog;
	private double listen_distance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mine);
	}

	@Override
	protected void initView() {
		userId = MyApplication.driverInfo.drivId;

		tv_my_account = findViewById(R.id.tv_my_account);
		tv_my_all_order = findViewById(R.id.tv_my_all_order);
		tv_contact_waiter = findViewById(R.id.tv_contact_waiter);
		tv_feedback = findViewById(R.id.tv_feedback);
		tv_check_version = findViewById(R.id.tv_check_version);

		tv_listen_order_distance = (TextView) findViewById(R.id.tv_listen_order_distance);
		btOnline = (Button) findViewById(R.id.btn_online);
		tv_modify_password = (TextView) findViewById(R.id.tv_modify_password);
		tv_is_special_car = (TextView) findViewById(R.id.tv_is_special_car);
		rl_listen_order_setting = (RelativeLayout) findViewById(R.id.rl_listen_order_setting);
		rl_set_is_special_car = (RelativeLayout) findViewById(R.id.rl_set_is_special_car);
		tv_is_special_car = (TextView) findViewById(R.id.tv_is_special_car);

		mBtMiddle.setText("设置");
		mBtMiddle.setVisibility(View.VISIBLE);

		mImgLeft.setVisibility(View.VISIBLE);
		mImgLeft.setBackgroundResource(R.drawable.back_bg_selector);

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tv_my_account:
			Intent intent = new Intent(this, MyAccountActivity.class);
			startActivity(intent);
			break;
		case R.id.rl_listen_order_setting:
			if (dialogDistance == null) {
				dialogDistance = new SetListenOrderDistanceDialog(this,
						new OnDialogDismissListener() {

							@Override
							public void onConfirmClicked(String distance) {
								// TODO Auto-generated method stub
								saveListenOrderDistance(distance);
							}

							@Override
							public void onCancelClicked() {
								// TODO Auto-generated method stub

							}

						});
			}
			dialogDistance.show();
			break;
		case R.id.rl_set_is_special_car:
			if (carDialog == null) {
				carDialog = new SetIsSpecialCarDialog(this,
						new SetIsSpecialCarDialog.OnDialogDismissListener() {
							
							@Override
							public void onConfirmClicked(int index) {
								// TODO Auto-generated method stub
								saveIsSpecialCar(index);
							}
							
							@Override
							public void onCancelClicked() {
								// TODO Auto-generated method stub
								
							}
						});
			}
			carDialog.show();
			
			break;
		case R.id.tv_my_all_order:
			startActivity(OrderListActivity.class);
			break;
		case R.id.tv_check_version:
			checkUpdate();
			break;
		case R.id.tv_contact_waiter:
			Intent intent3 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
					+ BusConstant.CONTACT_PHONE));
			startActivity(intent3);
			break;
		case R.id.tv_feedback:
			startActivity(FeedbackActivity.class);
			break;
		case R.id.btn_online:
			updateServiceStatus();
			break;
		case R.id.tv_modify_password:
			Intent intent2 = new Intent(this, ModifyPasswordActivity.class);
			startActivity(intent2);
			break;
		}
	}
	private void saveIsSpecialCar(final int index) {

		MyHttpUtil http = new MyHttpUtil();
		http.addBodyParm("driverId", "" + userId);

		if(index == 2){
			http.addBodyParm("orderType", "" + 4);
		}else{
			http.addBodyParm("orderType", "-1");
		}
		
		ProgressUtil.showProgress(this, "");
		http.send(Url.update_url, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				ProgressUtil.closeProgress();
				try {
					if (object.get("status").equals("0")) {
						ToastUtil.showToast("听单是否专线成功");
						if(index == 2){
							tv_is_special_car.setText("否");
						}else{
							tv_is_special_car.setText("是");
						}
					} else {
						toast(object.optString("msg", "数据加载出错，请重试"));
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void fail(String error) {
				ProgressUtil.closeProgress();
			}
		});
	}
	
	private void saveListenOrderDistance(final String distance) {

		MyHttpUtil http = new MyHttpUtil();
		http.addBodyParm("driverId", "" + userId);

		http.addBodyParm("distance", "" + Float.parseFloat(distance) / 100);
		ProgressUtil.showProgress(this, "");
		http.send(Url.update_url, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				ProgressUtil.closeProgress();
				try {
					if (object.get("status").equals("0")) {
						ToastUtil.showToast("听单距离更新成功");
						tv_listen_order_distance.setText(distance + " km");

					} else {
						toast(R.string.data_error);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void fail(String error) {
				ProgressUtil.closeProgress();
			}
		});
	}

	private void updateServiceStatus() {

		final LocationClient locationClient = new LocationClient(
				getApplicationContext());
		locationClient.setLocOption(MyLocationClient.getInstance(this)
				.getLocationOption());

		locationClient.registerLocationListener(new BDLocationListener() {

			@Override
			public void onReceiveLocation(BDLocation location) {
				double latitude = location.getLatitude();
				double longitude = location.getLongitude();
				MyApplication.instance().curLatitude = latitude;
				MyApplication.instance().curLongtitude = longitude;

				onLineSubmit(latitude, longitude);
				locationClient.stop();
			}

		});
		locationClient.start();

	}

	private void onLineSubmit(double latitude, double longitude) {
		String regionId = JPushInterface.getRegistrationID(this);
		if (CommonTools.isEmpty(regionId)) {
			toast("初始化推送失败，请退出后重试！");
			return;
		}

		MyHttpUtil http = new MyHttpUtil();
		http.addBodyParm("driverId", "" + userId);
		http.addBodyParm("currentLongtitude", "" + longitude);
		http.addBodyParm("currentLatitude", "" + latitude);

		switch (status) {
		case 2:
			http.addBodyParm("status", "" + 0); // type0("接单状态", 0),
												// type1("运营状态",
												// 1),type2("休息状态", 2);
			break;
		case 0:
			http.addBodyParm("status", "" + 2);
			break;
		case 1:
			toast("请先完成服务中订单");
			return;
		}

		http.addBodyParm("regionId", regionId);
		ProgressUtil.showProgress(this, "");
		http.send(Url.update_url, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				ProgressUtil.closeProgress();
				// {"msg":"ok","status":"0","result":{"message":null,"order":null,"dirverSize":null,"callStatus":0}}
				try {
					if (object.get("status").equals("0")) {
						object = object.getJSONObject("result");
						getDriverServiceStatus();
					} else {
						toast(R.string.data_error);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

			@Override
			public void fail(String error) {
				ProgressUtil.closeProgress();
			}
		});
	}

	@Override
	protected void initData() {

		getDriverServiceStatus();
	}

	@Override
	protected void setListeners() {
		rl_listen_order_setting.setOnClickListener(this);
		tv_my_account.setOnClickListener(this);
		tv_my_all_order.setOnClickListener(this);
		tv_contact_waiter.setOnClickListener(this);
		tv_feedback.setOnClickListener(this);
		tv_check_version.setOnClickListener(this);
		btOnline.setOnClickListener(this);
		tv_modify_password.setOnClickListener(this);
		rl_set_is_special_car.setOnClickListener(this);
		mImgLeft.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
	}

	private void getDriverServiceStatus() {
		MyHttpUtil http = new MyHttpUtil();
		http.addBodyParm("driverId", "" + userId);
		http.send(Url.get_service_status, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				// {"msg":"ok","status":"0","result":{"createTime":1453557865000,"distance":0.08,"drivId":1,"status":0,"currentLongtitude":116.293353,"orderType":0,"currentLatitude":40.200899,"remarks":"","carSeat":3,"cardType":0,"regionId":"090c90a21bf"}}
				// 0 接单、 1 运营中、 2 休息
				status = object.optJSONObject("result").optInt("status", 2);
				MyApplication.driverStatus = status;
				listen_distance = object.optJSONObject("result").optDouble("distance", 0.03);
				tv_listen_order_distance.setText((int)(listen_distance*100) + " 公里");
				int orderType = object.optJSONObject("result").optInt("orderType", 0);   //判断是否专线司机
				
				if(orderType == 4){
					tv_is_special_car.setText("是");
				}else{
					tv_is_special_car.setText("否");
				}
				
				switch (status) {
				case 0:
					btOnline.setText("已上线(点击离线)");
					btOnline.setBackgroundResource(R.drawable.green_btn_bg_selector);
					break;
				case 1:
					btOnline.setText("服务中");
					btOnline.setBackgroundResource(R.drawable.green_btn_bg_selector);
					break;
				default:
					btOnline.setText("已离线(点击上线)");
					btOnline.setBackgroundResource(R.drawable.orange_btn_bg_selector);
					break;
				}
			}

			@Override
			public void fail(String error) {
				Log.d("bus", error);
			}
		});
	}

	private void checkUpdate() {
		MyHttpUtil http = new MyHttpUtil();
		ProgressUtil.showProgress(this, "");
		http.send(Url.version_update, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				checkVersion(object);
			}

			@Override
			public void fail(String error) {
				ProgressUtil.closeProgress();
			}
		});
	}

	private void checkVersion(JSONObject object) {
		// "version": "20151201",
		// "url":
		// "http://club.autohome.com.cn/bbs/thread-c-3286-45161297-1.html",
		// "remarks": "升级了版本功能，麻烦升级哦！"

		try {
			int currentVersion = VersionUtil
					.getVersionCode(getApplicationContext());
			int version = object.optInt("version", 1);
			final String url = object.optString("url", "");
			if (version > currentVersion) {
				if (dialog == null) {
					dialog = new CommonAlertDialog(this, "更新", "取消",
							"有新版本来咯...",
							new CommonAlertDialog.OnDialogDismissListener() {
								@Override
								public void onConfirmClicked() {
									if (!CommonTools.isEmpty(url)) {
										Uri uri = Uri.parse(url);

										Intent intent = new Intent(
												Intent.ACTION_VIEW, uri);
										intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										MyApplication.instance().startActivity(
												intent);
									}
								}

								@Override
								public void onCancelClicked() {

								}
							});
					dialog.setOwnerActivity(this);
				}
				dialog.show();
			} else {
				toast("已经是最新版本");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out);
	}
}
